﻿namespace EquipmentAlarmSystem.Service.Library;

/// <summary>
/// 日志记录
/// </summary>
public class Logging(string logName, bool iSCach = true)
{
    /// <summary>
    /// 锁
    /// </summary>
    private static object _lock = new();

    string filePath = Path.Combine(Basics.BasicsPath, "log", logName);
    public static List<string> CacheLogs => cacheLogs;

    private static List<string> cacheLogs = new();
    private void Add(string item)
    {
        if (iSCach)
        {
            if (cacheLogs.Count >= 35)
            {
                cacheLogs.RemoveAt(0);
            }
            cacheLogs.Add(item);
        }
    }

    /// <summary>
    /// 信息
    /// </summary>
    public void Info(string content)
    {
        lock (_lock)
        {
            try
            {
                string journal = $"{Basics.GetDate}；Info；{content.Replace("\n", "")}";

                Add(journal);

                Console.WriteLine(journal);

                Basics.PathCheck(filePath);

                File.AppendAllText($"{filePath}/{DateTime.Now:D}.log", journal + "\n");
            }
            catch (Exception ex)
            {
                Error(ex.Message);
            }
        }
    }

    /// <summary>
    /// 警告
    /// </summary>
    public void Warning(string content)
    {
        lock (_lock)
        {
            try
            {
                string journal = $"{Basics.GetDate}；Warning；{content.Replace("\n", "")}";
                Add(journal);
                Console.WriteLine(journal);

                Basics.PathCheck(filePath);
                File.AppendAllText($"{filePath}/{DateTime.Now:D}.log", journal + "\n");
            }
            catch (Exception ex)
            {
                Error(ex.Message);
            }
        }
    }

    /// <summary>
    /// 错误
    /// </summary>
    public void Error(string content)
    {
        lock (_lock)
        {
            try
            {
                string journal = $"{Basics.GetDate}；Error；{content.Replace("\n", "")}";
                Add(journal);
                Console.WriteLine(journal);

                Basics.PathCheck(filePath);

                File.AppendAllText($"{filePath}/{DateTime.Now:D}.log", journal + "\n");
            }
            catch (Exception ex)
            {
                throw new(ex.Message);
            }
        }
    }
}
